/****************************************************************************/
/* Javascript that goes along with the dialog boxes in                      */
/* ManageBlogsFollowingDialogs.gxp                                          */
/****************************************************************************/

var dialogContentNode = null;
var dialogCallback = null;
var dialogErrorCallback = null;
var dialogCloseCallback = null;
var dialogBusyCallback = null;

/**
 * Opens a modal dialog with the specified domNode.
 */
function openDialog(domNodeId) {
  dialogContentNode = document.getElementById(domNodeId);

  // typically the dom node should be hidden since it's only visible in the
  // dialog box
  dialogContentNode.style.display = 'block';

  var locationEl = document.getElementById('body');
  BLOG_makeDialog(dialogContentNode, locationEl, true);
}

/**
 * Opens a modal dialog from the specified url.
 */
function openDialogFromUrl(url, callback) {
  // This dom node id is hardcoded into the BLOG_retrieveDialog function
  dialogContentNode = document.getElementById('dialogBox');

  var locationEl = document.getElementById('dialogLocation');
  BLOG_retrieveDialog(url, [], locationEl, true, callback);
}

/**
 * Closes the modal dialog box
 */
function closeDialog() {
  if (dialogCloseCallback) {
    dialogCloseCallback();
  }

  // return this node to the document body for future use
  dialogContentNode.style.display = 'none';
  document.body.appendChild(dialogContentNode);
  BLOG_cancelDialog(false);
}

/**
 * Goes to the next step in the "create subscription" dialog
 */
function dialogNextStep() {
  var validInput = false;
  if (dialogType == 'add') {
    // Check if at least one URL was added
    var urlInputs = document.getElementsByName('createSubscriptionDialogText');
    for (var i = 0; i < urlInputs.length; i++) {
      if (urlInputs[i].value != '') {
        validInput = true;
        break;
      }
    }
  } else if (dialogType == 'import') {
    // Check if at least one subscription was added
    var checkboxes = document.getElementsByName('subscriptionCheckbox');
    for (var i = 0; i < checkboxes.length; i++) {
      if (checkboxes[i].checked) {
        validInput = true;
        break;
      }
    }
  }

  if (validInput) {
    d('dialogError').style.display = 'none';
    d('add1').style.display = 'none';
    d('add2').style.display = 'block';
  } else {
    d('dialogError').style.display = 'block';
  }
}

/**
 * Opens the "Create subscription" dialog and blanks out form field contents.
 * @param successCallback Js callback called when a subscription is successful.
 * It takes a list of subscription objects.
 * @param errorCallback JS callback called when an error occurs on import
 * importCallback takes a JSON object with one string "error" and other
 * optional members.
 * @param opt_closeCallback Optional callback to call when the dialog is closed
 * for any reason (eg: cancel).
 * @param opt_busyCallback Optional callback to call when the dialog is closed
 * due to a successful submit (not cancel, not dupes). This is called WHILE
 * the ajax call is in flight, as opposed to success/errorCallback, which
 * are called when the ajax call comes back.
 */
function openCreateSubscriptionDialog(successCallback,
                                      errorCallback,
                                      opt_closeCallback,
                                      opt_dialogBusyCallback) {
  // Stash the callbacks for later
  dialogCallback = successCallback;
  dialogErrorCallback = errorCallback;
  dialogCloseCallback = opt_closeCallback;
  dialogBusyCallback = opt_dialogBusyCallback;

  var dialog = document.getElementById('createSubscriptionDialog');
  if (dialog) {
    // If we've opened the dialog before just trash it and reopen it since
    // we need a new captcha
    dialog.parentNode.removeChild(dialog);
  }

  // Open the dialog
  openDialogFromUrl('manage-blogs-following.g?isDialogRequest=true',
      function() {
        // Reset the dialog type
        selectDialogType('add');
        document.getElementById('addRadio').checked = true;

        // This is a hack to find and eval JS in the dom since it won't get
        // loaded automatically.
        // TODO(henrywong): The list you get from FRBE should just be exposed
        // as a json servlet that gets pulled in via another hit
        if (d('onloadScript')) {
          eval(d('onloadScript').innerHTML);
        }
      });
}

/**
 * Function to do UI morphing of createSubscriptionDialog
 */
var dialogType = null;
function selectDialogType(type) {
  dialogType = type;
  if (type == 'add') {
    document.getElementById('importOnlyMain').style.display = 'none';
    document.getElementById('createOnlyMain').style.display = '';
  } else if (type == 'import') {
    document.getElementById('importOnlyMain').style.display = '';
    document.getElementById('createOnlyMain').style.display = 'none';
  }
}

/**
 * Called when the user clicks the "add" button from the createSubscription
 * dialog. Invokes the callback.
 */
function createSubscription() {
  // Find out which bloglists this is getting added to
  var blogListIds = new Array();
  var blogListCheckboxes = document.getElementsByName('blogListCheckbox');
  for (var i = 0; i < blogListCheckboxes.length; i++) {
    if (blogListCheckboxes[i].checked) {
      blogListIds.push(blogListCheckboxes[i].value);
    }
  }

  if (typeof(BLOG_readingList) != 'undefined') {
    BLOG_readingList.displayLoadingMessage();
  }

  if (dialogType == 'add') {
    // Determine which URLs were selected
    var urls = new Array();
    var urlInputs = document.getElementsByName('createSubscriptionDialogText');
    for (var i = 0; i < urlInputs.length; i++) {
      if (urlInputs[i].value != '') {
        // Add http:// to any urls that don't have a protocol
        var url = urlInputs[i].value;
        if (url.indexOf('://') == -1) {
          url = 'http://' + url;
        }

        urls.push(url);
      }
    }

    if (urls != null) {

      // Run the "busy" callback if one is specified
      if (dialogBusyCallback) {
        dialogBusyCallback();
      }

      createSubscriptionOnServer(urls,
          document.getElementById('followAnonRadio').checked,
          blogListIds,
          dialogCallback,
          dialogErrorCallback);
    }
  } else if (dialogType == 'import') {
    // Determine which subscriptions were selected
    var feedUrls = new Array();
    var checkboxes = document.getElementsByName('subscriptionCheckbox');
    for (var i = 0; i < checkboxes.length; i++) {
      if (checkboxes[i].checked) {
        feedUrls.push(checkboxes[i].value);
      }
    }

    // Run the "busy" callback if one is specified
    if (dialogBusyCallback) {
      dialogBusyCallback();
    }

    // Both "import from reader" and "import blog you're following" use the
    // same callback
    importSubscriptionOnServer(feedUrls,
        document.getElementById('followAnonRadio').checked,
        blogListIds,
        dialogCallback,
        dialogErrorCallback);
  }
}

/**
 * Creates more URL inputs in the "createSubscription" dialog
 */
function addMoreUrls() {
  var input = document.createElement('input');
  input.type = 'text';
  input.id = 'createSubscriptionDialogText';
  input.name = 'createSubscriptionDialogText';
  input.size = 50;

  var container =
      document.getElementById('createSubscriptionDialogTextContainer');
  container.appendChild(document.createElement('br'));
  container.appendChild(input);
}

var importMap = [];
/**
 * Takes a map of String > [String, String...] which contains a list of all
 * of the tagnames and the stream ids they map to
 */
function addToImportMap(key, val) {
  if (!importMap[key]) {
    importMap[key] = new Array();
  }
  importMap[key].push(val);
}

function selectAllImports() {
  var checkboxes = document.getElementsByName('subscriptionCheckbox');
  for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = true;
  }
  updateImportCount();
}

function selectNoImports() {
  var checkboxes = document.getElementsByName('subscriptionCheckbox');
  for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = false;
  }
  updateImportCount();
}

function selectFolderImports(folderId, select) {
  var idList = importMap[folderId];
  if (idList) {
    for (var i = 0; i < idList.length; i++) {
      document.getElementById('subscriptionCheckbox-' + idList[i]).checked =
        select;
    }
    updateImportCount();
  }
}

function updateImportCount() {
  var importCount = 0;
  var checkboxes = document.getElementsByName('subscriptionCheckbox');
  for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].checked) {
      importCount++;
    }
  }
  document.getElementById('subscriptions-for-import-count').innerHTML =
    importCount;
}

/****************************************************************************/
/* Random Utilities                                                         */
/****************************************************************************/

/**
 * Sends an HTTP Post to the specified URL.
 * @param data A JS object that contains a mapping of name/value pairs to pass
 * as the parameters of the POST.
 */
function sendHttpPost(url, data, successCallback, errorCallback) {
  var req = XH_XmlHttpCreate();
  var handler = function() {
    if (req.readyState == XML_READY_STATE_COMPLETED) {
      if (req.status == 200) {
        // Need to wrap this in parenthesis for the eval to work
        var str = '(' + req.responseText + ')';
        var resp = eval(str);
        successCallback(resp);
      } else if (errorCallback) {
        // Don't try to eval this b/c there's a large chance that it's
        // just some random HTML from the server
        errorCallback(req.responseText);
      }
    }
  }

  var dataStr = 'security_token=' + BLOG_securityToken + '&';

  for (var i in data) {
    if (dataStr.length > 0) {
      dataStr = dataStr + '&';
    }

    if (data[i] instanceof Array) {
      // If it's an array, unroll it
      for (var j = 0; j < data[i].length; j++) {
        if (j > 0) {
          dataStr = dataStr + '&';
        }
        dataStr = dataStr + i + '=' + encodeURIComponent(data[i][j]);
      }
    } else {
      // It's a string
      dataStr = dataStr + i + '=' + encodeURIComponent(data[i]);
    }
  }

  XH_XmlHttpPOST(
      req,
      url,
      dataStr,
      handler);
}

/****************************************************************************/
/* Various AJAX routines                                                    */
/****************************************************************************/

/**
 * Performs ajax call to create a subscription on the server. If successful,
 * ajax callback creates the subscription in the UI.
 */
function createSubscriptionOnServer(urls, isPrivate, blogListIds,
                                    successCallback, errorCallback) {
  // Assemble the POST
  var dataObj = {
    'action': 'CREATE_EXTERNAL',
    'isPrivate': isPrivate ? 'true' : 'false',
    'blogListIds': blogListIds,
    'externalUrls': urls
  };

  addCaptchaArgs(dataObj);

  sendHttpPost('manage-blogs-following.do',
      dataObj,
      successCallback,
      errorCallback);
}

/**
 * Performs ajax call to create a subscription on the server. If successful,
 * ajax callback creates the subscription in the UI.
 */
function importSubscriptionOnServer(feedUrls, isPrivate, blogListIds,
                                    successCallback, errorCallback) {
  // Assemble the POST
  var dataObj = {
    'action': 'CREATE_INTERNAL',
    'isPrivate': isPrivate ? 'true' : 'false',
    'blogListIds': blogListIds,
    'feedUrls': feedUrls
  };

  addCaptchaArgs(dataObj);

  sendHttpPost('manage-blogs-following.do',
      dataObj,
      successCallback,
      errorCallback);
}

function addCaptchaArgs(dataObj) {
  // If there was a captcha, add it.
  // recaptcha_challenge_field is copied from
  // CaptchaClient.RECAPTCHA_TOKEN_PARAM_NAME,
  // recaptcha_response_field is copied from
  // CaptchaClient.RECAPTCHA_ANSWER_PARAM_NAME
  if (document.getElementById('recaptcha_challenge_field')) {
    dataObj.recaptcha_challenge_field =
        document.getElementById('recaptcha_challenge_field').value;
    dataObj.recaptcha_response_field =
        document.getElementById('recaptcha_response_field').value;
  }
}

function setPrivacyOnServer(key, value, successCallback, errorCallback) {
  // Assemble the POST
  // TODO(henrywong): THE NAME SHOULD NOT BE NECESSARY
  var dataObj = {
    'action': 'UPDATE_PRIVACY',
    'key': key,
    'isPrivate': value
  };

  // Send the data back to the server
  sendHttpPost('manage-blogs-following.do',
      dataObj,
      function() {
        successCallback(key, value);
      },
      errorCallback);
}

function deleteSubscriptionOnServer(key, successCallback, errorCallback) {
  // Assemble the POST
  var dataObj = {
    'action': 'DELETE',
    'key': key
  };

  // Send the data back to the server
  sendHttpPost('manage-blogs-following.do',
      dataObj,
      function() {
        successCallback(key);
      },
      errorCallback);
}
